const fs = require("fs");
const path = require("path");
const formidable = require("formidable");
const avatarPath = path.join(path.resolve(__dirname, '../..'), '/public/images/avatars');


const uploadfile = (ctx, Path, id) => {
    const form = formidable({
        multipart: true,
        uploadDir: Path,
        keepExtensions: true,
        allowEmptyFiles: false
    });
    return new Promise((resolve, reject) => {
        form.parse(ctx.req, async (err, fields, files) => {//ctx.req原生的node的http请求模块；ctx.require.body是经过koa二次封装之后的
            if (err) {
                reject(err);
                return;
            }
            let keys = Object.keys(files);//获取files对象中的属性名[formData传入的图片]
            keys?.map(async (key) => {
                let { size, filepath, newFilename, originalFilename, mimetype } = files[key];
                console.log(originalFilename, "yuanxiandemingzi");
                let sql = 'update course set course_image=? where course_id=?';
                let result = await ctx.db.EXCUTE(sql, [originalFilename, id]);
                console.log('uploadRes:', result);
                // 将文件重命名为原本的文件名
                fs.rename(path.join(Path, `/${newFilename}`), path.join(Path, `/${originalFilename}`),
                    (err) => {
                        if (err) {
                            console.log(err);
                        } else {
                            console.log('file is reset!');
                        }
                    })
            })
            resolve({ code: 200, fields, files });
        });
    });
}

const uploadAvatar = (ctx, Path, id, tableName) => {
    const form = formidable({
        multipart: true,
        uploadDir: Path,
        keepExtensions: true,
        allowEmptyFiles: false
    });
    return new Promise((resolve, reject) => {
        console.log("执行了函数");
        form.parse(ctx.req, async (err, fields, files) => {//ctx.req原生的node的http请求模块；ctx.require.body是经过koa二次封装之后的
            if (err) {
                reject(err);
                return;
            }
            console.log(Object.keys(fields).length, "formData的长度");
            let sql = `select avatar from ${tableName} where user_id = ?`
            let res = await ctx.db.EXCUTE(sql, [id]);
            if (res[0].avatar) {
                fs.stat(path.join(Path, res[0].avatar), (err, state) => {
                    if (err) {
                        console.log(err);
                        throw new Error(err.message);
                    } else {
                        fs.unlinkSync(path.join(Path, res[0].avatar));
                    }
                })
            }
            console.log("开始执行");
            let keys = Object.keys(files);//获取files对象中的属性名[formData传入的图片] 
            keys?.map(async (key) => {
                console.log(files[key]);
                let { size, filepath, newFilename, originalFilename, mimetype } = files[key];
                // console.log(originalFilename);
                let sql = 'update ' + tableName + ' set avatar = ? where user_id = ?'
                console.log(sql);
                // let sql = 'update course set course_image=? where course_id=?';
                let Filename = Date.now() + '.' + originalFilename.split('.')[1];
                let result = await ctx.db.EXCUTE(sql, [Filename, id]);
                console.log('uploadRes:', result);

                console.log(Filename, "新的文件名称");
                console.log(originalFilename, "原先的文件名称");
                // 将文件重命名为原本的文件名
                fs.rename(path.join(Path, `/${newFilename}`), path.join(Path, `/${Filename}`),
                    (err) => {
                        if (err) {
                            console.log(err);
                        } else {
                            console.log('file is reset!');
                        }
                    })
            })
            resolve({ code: 200, fields, files });
        });
    });
}
// 上传课程图片
const uploadCourseImg = (ctx, Path, id) => {
    const form = formidable({
        multipart: true,
        uploadDir: Path,
        keepExtensions: true,
        allowEmptyFiles: false
    });
    return new Promise((resolve, reject) => {
        console.log("执行了函数");
        form.parse(ctx.req, async (err, fields, files) => {//ctx.req原生的node的http请求模块；ctx.require.body是经过koa二次封装之后的
            if (err) {
                reject(err);
                return;
            }
            console.log(Object.keys(fields).length, "formData的长度");
            let sql = `select course_image from course where course_id = ?`
            let res = await ctx.db.EXCUTE(sql, [id]);
            if (res[0].course_image) {
                fs.stat(path.join(Path, res[0].course_image), (err, state) => {
                    if (err) {
                        console.log(err);
                        throw new Error(err.message);
                    } else {
                        fs.unlinkSync(path.join(Path, res[0].course_image));
                    }
                })
            }
            console.log("开始执行");
            let keys = Object.keys(files);//获取files对象中的属性名[formData传入的图片] 
            keys?.map(async (key) => {
                console.log(files[key]);
                let { size, filepath, newFilename, originalFilename, mimetype } = files[key];
                // console.log(originalFilename);
                let sql = 'update course set course_image = ? where course_id = ?'
                console.log(sql);
                // let sql = 'update course set course_image=? where course_id=?';
                let Filename = Date.now() + '.' + originalFilename.split('.')[1];
                let result = await ctx.db.EXCUTE(sql, [Filename, id]);
                console.log('uploadRes:', result);

                console.log(Filename, "新的文件名称");
                console.log(originalFilename, "原先的文件名称");
                // 将文件重命名为原本的文件名
                fs.rename(path.join(Path, `/${newFilename}`), path.join(Path, `/${Filename}`),
                    (err) => {
                        if (err) {
                            console.log(err);
                        } else {
                            console.log('file is reset!');
                        }
                    })
            })
            resolve({ code: 200, fields, files });
        });
    });
}



module.exports = {
    uploadfile,
    uploadAvatar,
    uploadCourseImg
}